#!/usr/bin/env python
# $Id: sysbackup.py df54dec975f4 2012/09/09 20:22:40 pgurumur $
# Copyright (c) 2012 Prabhu Gurumurthy <pgurumur@gmail.com>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

__version__  = "$Revision: df54dec975f4 $"
__author__   = "$Author: pgurumur $"
__modified__ = "$Date: 2012-09-09 20:22:40Z $"

import optparse
import os
import subprocess
import sys

from sqlalchemy import Column, Integer, String, Numeric, Unicode
from sqlalchemy.ext.declarative import declarative_base

from venya.lib import cmdparser
from venya.lib import ip
from venya.lib import scm
from venya.lib import snmp
from venya.lib import sql
from venya.lib import stdlib

class ModelError(Exception):
   pass

Base = declartive_base()
class Device(Base):
   __tablename__ = u'device'

   pk = Column(Integer, primary_key = True)
   device = Column(Unicode(75), nullable = False)
   ipaddr = Column(Numeric(40, 0), nullable = False)
   community = Column(Unicode(75), nullable = False)
   digest = Column(Unicode(150), nullable = False)
   lastupdate = Column(Numeric(11, 7), nullable = False)
   descr = Column(Unicode(75), nullable = True)

   def __init__(self, **kwargs):
      super(Device, self).__init__()
      if "device" in kwargs:
         self.device = kwargs["device"]

      if "ipaddr" in kwargs:
         self.ipaddr = kwargs["ipaddr"]

      if "community" in kwargs:
         self.community = kwargs["community"]

      if "digest" in kwargs:
         self.digest = kwargs["digest"]

      if "descr" in kwargs:
         self.descr = kwargs["descr"]

      self.lastupdate = time.time()

   @property
   def update(self):
      return datetime.date.fromtimestamp(self.lastupdate)

class sysbackup(cmdparser.GetOpt):
   option_list = (
         optparse.make_option("-d", "--database", type = "str",
            help = "Database for backups", default = "/var/etc/backup.db",
            dest = "database"),
         optparse.make_option("-D", "--directory", type = "str",
            help = "Directory to backup", dest = "directory"),
         optparse.make_option("-c", "--community", type = "str",
            help = "Read/Write SNMP v2 community string", dest = "community"),
         optparse.make_option("-n", "--dryrun", action = "store_true",
            help = "Dry run, without actual work", default = False,
            dest = "dryrun"),
         optparse.make_option("-N", "--name", type = "str",
            help = "DNS name of the device", dest = "name"),
         ) + cmdparser.GetOpt.option_list

   def __init__(self, **kwargs):
      super(self.__class__, self).__init__(**kwargs)
      self._sql = None
      self._comm = None

   def create(self, engine):
      if engine:
         try:
            Base.metadata.create_all(engine)
         except OperationalError as err:
            self.error(err)
      else:
         self.error("no engine defined!")

   def handle(self):
      (options, args) = self.parse()
      hosts = []
      try:
         hosts = args[1:]
      except IndexError:
         pass

      if options.database and os.path.exists(options.database):
         self._sql = sql.sqlite(options.database, bool(options.verbosity))

         try:
            self.create(self._sql.engine)
         except sql.SQLError as err:
            self.error(err)

      if options.community:
         self._comm = options.community


if __name__ == "__main__":
   backup = None
   try:
      backup = sysbackup(version = 1, args = sys.argv)
      if len(backup) <= 1:
         backup.printhelp()
      else:
         backup.handle()
   except cmdparser.GetOptError, message:
      print message
      sys.exit(1)
